package dao;

import entity.Address;
import entity.Cart;
import utils.JDBCUtil;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class CartDao {
    public List<Cart> fetchCartItems(int userId) throws SQLException {
        // 定义 SQL 查询语句
        String sql = "SELECT sc.cart_id, sc.user_id, sc.product_id, " +
                "    sc.quantity, sc.added_at, p.PRODUCT_NAME, " +
                "    p.PRODUCT_DESCRIPTION, p.PRICE, p.IMAGE, p.user_id as shop_id " +
                "FROM shopping_cart sc JOIN " +
                "    products p ON sc.product_id = p.PRODUCT_ID " +
                "WHERE \n" +
                "    sc.user_id = ?;";

        // 创建结果列表
        List<Cart> cartItems = new ArrayList<>();

        // 使用 try-with-resources 确保资源正确关闭
        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            // 设置参数
            preparedStatement.setInt(1, userId);

            // 执行查询
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                // 遍历结果集
                while (resultSet.next()) {
                    // 创建 Cart 对象实例
                    Cart cart = new Cart();
                    cart.setCartId(resultSet.getInt("cart_id"));
                    cart.setUserId(resultSet.getInt("user_id"));
                    cart.setProductId(resultSet.getInt("product_id"));
                    cart.setQuantity(resultSet.getInt("quantity"));
                    cart.setAddedAt(resultSet.getObject("added_at", LocalDateTime.class));

                    // 设置商品信息
                    cart.setProductName(resultSet.getString("PRODUCT_NAME"));
                    cart.setProductDescription(resultSet.getString("PRODUCT_DESCRIPTION"));
                    cart.setPrice(resultSet.getDouble("PRICE"));
                    cart.setImage(resultSet.getString("IMAGE"));
                    cart.setShopId(resultSet.getInt("shop_id"));

                    // 添加到结果列表
                    cartItems.add(cart);
                }
            }
        }
        return cartItems;
    }


    public void updateItemQuantity(String itemId, int delta) {
        String sql = "UPDATE shopping_cart SET quantity = quantity +? WHERE cart_id =?";
        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置第一个参数，即数量的变化量delta
            preparedStatement.setInt(1, delta);
            preparedStatement.setString(2, itemId);
            // 执行更新操作
            int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("商品数量更新成功");
            } else {
                System.out.println("未找到对应的商品记录，更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("更新商品数量时出现数据库操作异常");
        }
    }


    public void removeItem(String itemId) {
        String sql = "delete from shopping_cart WHERE cart_id =?";
        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置第一个参数，即购物车id itemId
            int cart_id = Integer.parseInt(itemId);
            preparedStatement.setInt(1, cart_id);
            // 执行更新操作
            int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("商品删除成功");
            } else {
                System.out.println("未找到对应的商品记录，删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("删除商品时出现数据库操作异常");
        }
    }

    public void moveToFavorites(String itemId) {
        // 实现移动到收藏夹逻辑
    }

    public void batchDeleteItems(List<Integer> itemIds) throws SQLException {
        String sql = "DELETE FROM shopping_cart WHERE cart_id = ?";

        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // 开始批处理
            for (int itemId : itemIds) {
                pstmt.setInt(1, itemId); // 设置参数
                pstmt.addBatch(); // 添加到批处理中
            }

            // 执行批量删除
            int[] results = pstmt.executeBatch();

            for (int result : results) {
                // 根据实际需求，可以添加日志或其他处理
                if (result == 0) {
                    // 删除失败的情况（可以做错误处理）
                    System.out.println("某个商品未能删除");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new SQLException("批量删除失败", e);
        }
    }

    public void addItem(int userId, int productId, int quantity, Timestamp addedAt) {
        String check = "SELECT quantity FROM shopping_cart WHERE user_id = ? AND product_id = ?";
        String update = "UPDATE shopping_cart SET quantity = quantity + ? WHERE user_id = ? AND product_id = ?";
        String insert = "INSERT INTO shopping_cart (user_id, product_id, quantity, added_at) VALUES (?, ?, ?, ?)";



        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement checkStmt = conn.prepareStatement(check);
             PreparedStatement updateStmt = conn.prepareStatement(update);
             PreparedStatement insertStmt = conn.prepareStatement(insert)
        ){
            // 检查是否已存在相同的用户和商品记录
            checkStmt.setInt(1, userId);
            checkStmt.setInt(2, productId);
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                // 如果记录已存在，更新数量
                updateStmt.setInt(1, quantity);
                updateStmt.setInt(2, userId);
                updateStmt.setInt(3, productId);
                updateStmt.executeUpdate();
            } else {
                // 如果记录不存在，插入新记录
                insertStmt.setInt(1, userId);
                insertStmt.setInt(2, productId);
                insertStmt.setInt(3, quantity);
                insertStmt.setTimestamp(4, addedAt);
                insertStmt.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("添加商品到购物车失败", e);
        }
    }

    public Address getDefaultAddress(int userId) {
        String query = "SELECT PEICE_NAME, PHONE, PROVINCE, DISTRICT, DETAIL_ADDRESS " +
                "FROM users WHERE USER_ID = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setInt(1, userId); // 设置用户ID
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    // 将查询结果封装为 Address 对象
                    Address address = new Address();
                    address.setPeiceName(rs.getString("PEICE_NAME"));
                    address.setPhone(rs.getString("PHONE"));
                    address.setProvince(rs.getString("PROVINCE"));
                    address.setDistrict(rs.getString("DISTRICT"));
                    address.setDetailAddress(rs.getString("DETAIL_ADDRESS"));
                    return address;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询默认收货地址失败！", e);
        }
        return null; // 如果未找到地址，返回 null
    }

    public void deleteAllItems(int userId) {
        String sql = "DELETE FROM shopping_cart WHERE user_id = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("删除购物车所有商品失败！", e);
        }
    }
}

